package com.zrf.gulimall.order.interceptor;

import com.zrf.gulimall.commnon.core.vo.MemberResponseVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @Author zhanrf
 * @Date 2022/1/6 21:20
 */
public class LoginInterceptor implements HandlerInterceptor {
	public static ThreadLocal<MemberResponseVo> LOGIN_USER = new ThreadLocal<>();

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uri = request.getRequestURI();
		AntPathMatcher antPathMatcher = new AntPathMatcher();
		boolean match = antPathMatcher.match("/order/order/status/**", uri);
		boolean match1 = antPathMatcher.match("/payed/notify", uri);
		if (match || match1) {
			return true;
		}
		HttpSession session = request.getSession();
		MemberResponseVo loginUser = (MemberResponseVo) session.getAttribute("loginUser");
		if (Objects.isNull(loginUser)) {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.println("<script>alert('请先进行登录，再进行后续操作！');location.href='http://auth.gulimall.com/login.html'</script>");
			return false;
		}
		//把登录后用户的信息放在ThreadLocal里面进行保存
		LOGIN_USER.set(loginUser);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// 执行完后将threadlocal清空，防止内存泄漏
		LOGIN_USER.remove();
	}
}
